<template>
  <el-dialog v-model="visible" title="选择活动" width="80%" :before-close="handleClose">
    <!-- 搜索栏 -->
    <div class="handle-box">
      <el-input v-model="searchForm.title" placeholder="活动标题" class="handle-input mr10" clearable />
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border class="table" ref="activityTable" header-cell-class-name="table-header"
      row-key="id" @row-click="handleRowClick" :row-class-name="getRowClassName">
      <el-table-column label="选择" width="80" align="center">
        <template #default="scope">
          <el-radio v-model="selectedActivityId" :label="scope.row.id" @change="handleRadioChange(scope.row)">
            <span></span>
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="活动ID" width="80" />
      <el-table-column label="发布者头像" width="100">
        <template #default="scope">
          <el-image v-if="scope.row.publisherAvatar" :src="scope.row.publisherAvatar"
            style="width:40px;height:40px;border-radius:50%;" fit="cover"
            :preview-src-list="[scope.row.publisherAvatar]" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="发布者昵称/ID">
        <template #default="scope">
          <div v-if="scope.row.publisherName || scope.row.publisherId">
            {{ scope.row.publisherName || '-' }} / {{ scope.row.publisherId || '-' }}
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="封面">
        <template #default="scope">
          <div v-if="scope.row.imgUrl || scope.row.videoUrl" style="display: flex; justify-content: center;">
            <!-- 图片封面 -->
            <el-image v-if="scope.row.imgUrl" :src="scope.row.imgUrl" style="width:60px;height:60px;border-radius:4px;"
              fit="cover" :preview-src-list="[scope.row.imgUrl]" />
            <!-- 视频封面缩略图 -->
            <div v-else-if="scope.row.videoUrl"
              style="width:60px;height:60px;border-radius:4px;background:#f5f5f5;display:flex;align-items:center;justify-content:center;cursor:pointer;border:1px solid #ddd;position:relative;"
              @click="openVideoDialog(scope.row.videoUrl)">
              <video :src="scope.row.videoUrl" style="width:100%;height:100%;object-fit:cover;border-radius:4px;"
                muted />
              <div
                style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.6);border-radius:50%;width:24px;height:24px;display:flex;align-items:center;justify-content:center;">
                <i class="el-icon-video-play" style="font-size:12px;color:#fff;"></i>
              </div>
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="轮播图">
        <template #default="scope">
          <span v-if="!scope.row.imgList || scope.row.imgList.length === 0">-</span>
          <el-button v-else type="primary" size="mini" @click="openMediaDialog(scope.row.carouselMediaList)">
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题">
        <template #default="scope">
          <div class="content-cell">
            {{ scope.row.title || '-' }}
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="topic" label="话题" >
        <template #default="scope">
          {{ scope.row.topic || '-' }}
        </template>
      </el-table-column> -->
      <el-table-column prop="paymentAmount" label="价格">
        <template #default="scope">
          {{ scope.row.paymentAmount ? `¥${scope.row.paymentAmount}` : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="activityLocation" label="位置">
        <template #default="scope">
          {{ scope.row.activityLocation || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="signUpStartTime" label="报名开始时间">
        <template #default="scope">
          {{ dateFormat(scope.row.signUpStartTime) || "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="signUpEndTime" label="报名结束时间">
        <template #default="scope">
          {{ dateFormat(scope.row.signUpEndTime) || "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="activityTime" label="开始时间">
        <template #default="scope">
          {{ dateFormat(scope.row.activityTime) || "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="发布时间">
        <template #default="scope">
          {{ dateFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
      </el-pagination>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selected-info">{{ selectedActivity ? `已选择：${selectedActivity.title}` : '请选择活动' }}</span>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :disabled="!selectedActivity">确定</el-button>
        </div>
      </div>
    </template>
  </el-dialog>

  <!-- 媒体预览弹窗 -->
  <el-dialog v-model="mediaDialog.visible" width="40%" title="媒体预览" append-to-body>
    <div style="display: flex; justify-content: center;">
      <media-view v-if="mediaDialog.list.length" :list="mediaDialog.list" />
    </div>
  </el-dialog>

  <!-- 视频播放弹窗 -->
  <el-dialog v-model="videoDialog.visible" width="50%" title="视频播放" append-to-body @close="closeVideoDialog">
    <div style="display: flex; justify-content: center;">
      <video v-if="videoDialog.url" :src="videoDialog.url" controls style="max-width: 100%; max-height: 60vh;"
        ref="videoPlayer" @loadstart="onVideoLoadStart" @error="onVideoError">
      </video>
    </div>
  </el-dialog>
</template>

<script>
import moment from "moment";
import MediaView from "@/components/mediaVIew.vue";
import { getActivities } from "@/api/content";

export default {
  name: "SelectActivity",
  components: {
    MediaView
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    // 已选中的活动数据
    selectedData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      searchForm: {
        title: "",
      },
      tableData: [],
      selectedActivity: null, // 当前选中的活动
      selectedActivityId: null, // 当前选中的活动ID
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      mediaDialog: {
        visible: false,
        list: [],
      },
      // 视频播放弹窗
      videoDialog: {
        visible: false,
        url: '',
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.getData();
        this.initSelectedData();
      }
    },
    // 监听视频弹窗关闭，确保视频停止播放
    'videoDialog.visible'(newVal) {
      if (!newVal) {
        this.$nextTick(() => {
          if (this.$refs.videoPlayer) {
            this.$refs.videoPlayer.pause();
            this.$refs.videoPlayer.currentTime = 0;
          }
        });
      }
    }
  },

  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        // 必须的分页参数
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      // 根据搜索表单构建查询参数
      if (this.searchForm.title) {
        params.title = this.searchForm.title;
      }

      return params;
    },
    buildMediaList(item) {
      const mediaList = [];

      if (item.imgUrl) {
        mediaList.push({
          type: 'image',
          url: item.imgUrl
        });
      }

      if (item.videoUrl) {
        mediaList.push({
          type: 'video',
          url: item.videoUrl
        });
      }

      return mediaList;
    },

    // 构建轮播图媒体列表
    buildCarouselMediaList(item) {
      const mediaList = [];

      if (item.imgList && Array.isArray(item.imgList)) {
        item.imgList.forEach(imgUrl => {
          if (imgUrl) {
            mediaList.push({
              type: 'image',
              url: imgUrl
            });
          }
        });
      }

      return mediaList;
    },

    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getActivities(params);

        if (response && response.data) {
          this.tableData = response.data.rows.map(item => ({
            id: item.id,
            publisherAvatar: item.publisherAvatar || '',
            publisherName: item.publisherName || '',
            publisherId: item.publisherId || '',
            imgUrl: item.imgUrl,
            videoUrl: item.videoUrl,
            mediaList: this.buildMediaList(item),
            imgList: item.imgList || [], // 轮播图
            carouselMediaList: this.buildCarouselMediaList(item), // 轮播图媒体列表
            title: item.title,
            topic: item.topic || '',
            paymentAmount: item.paymentAmount,
            activityLocation: item.activityLocation,
            signUpStartTime: item.signUpStartTime, // 报名开始时间
            signUpEndTime: item.signUpEndTime, // 报名结束时间
            activityTime: item.activityTime,
            createTime: item.createTime,
            // 保留原始数据
            _original: item
          }));

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }

          // 数据加载完成后，设置已选中的数据
          this.$nextTick(() => {
            this.setSelectedRow();
          });
        }
      } catch (error) {
        console.error('获取活动数据失败:', error);
        this.$message.error('获取活动数据失败');
      }
    },
    openMediaDialog(list) {
      this.mediaDialog.list = list || [];
      this.mediaDialog.visible = true;
    },
    // 打开视频播放弹窗
    openVideoDialog(videoUrl) {
      this.videoDialog.url = videoUrl;
      this.videoDialog.visible = true;
    },
    // 关闭视频播放弹窗
    closeVideoDialog() {
      // 暂停并重置视频
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.pause();
        this.$refs.videoPlayer.currentTime = 0;
      }
      this.videoDialog.visible = false;
      this.videoDialog.url = '';
    },
    // 视频开始加载
    onVideoLoadStart() {
      console.log('视频开始加载');
    },
    // 视频加载错误
    onVideoError(error) {
      console.error('视频加载失败:', error);
      this.$message.error('视频加载失败，请检查视频链接是否有效');
    },
    // 初始化已选中的数据
    initSelectedData() {
      this.selectedActivity = this.selectedData;
      this.selectedActivityId = this.selectedData ? this.selectedData.id : null;
    },
    // 设置表格中已选中的行
    setSelectedRow() {
      // radio模式下不需要设置表格选中状态
    },
    // 处理radio选择变化
    handleRadioChange(row) {
      this.selectedActivity = row;
      this.selectedActivityId = row.id;
    },
    // 处理行点击事件
    handleRowClick(row) {
      this.selectedActivity = row;
      this.selectedActivityId = row.id;
    },
    // 获取行的class名称，用于高亮选中行
    getRowClassName({ row }) {
      return this.selectedActivityId === row.id ? 'selected-row' : '';
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false;
    },
    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.selectedActivity);
      this.handleClose();
    }
  },

};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.content-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}

// 选中行的样式
::v-deep .selected-row {
  background-color: #f0f9ff !important;
}

// 鼠标悬停时的指针样式
::v-deep .el-table__row {
  cursor: pointer;
}
</style>